package com.ny.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class EmailService {
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${spring.mail.username}")
    private String fromEmail;

    public void sendEmail(String toEmail, String code) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(toEmail);
            message.setSubject("重置密码验证码");
            message.setText("验证码为：" + code);
            
            // 添加日志记录
            System.out.println("准备发送邮件到: " + toEmail);
            mailSender.send(message);
            System.out.println("邮件发送成功");
            
            try {
                ValueOperations<String, String> ops = redisTemplate.opsForValue();
                // 设置验证码5分钟过期
                ops.set(toEmail, code, 5, TimeUnit.MINUTES);
                System.out.println("验证码已存储到Redis");
            } catch (Exception redisEx) {
                System.err.println("存储验证码到Redis时发生异常: " + redisEx.getMessage());
                // 可以选择继续抛出异常或者只记录日志
                // 这里我们选择只记录日志，让邮件发送成功
            }
        } catch (Exception e) {
            System.err.println("发送邮件时发生异常: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("邮件发送失败，请检查邮件服务配置", e);
        }
    }

    public String getCode() {
        int code = (int)((Math.random()*9000)+1000);
        return String.valueOf(code);
    }
}